import {
  zg99Request,
  jiatuiRequest,
  hbappRequest,
  appRequest,
  uploadFileRequest,
  eoffcnRequest,
} from "/utils/requests";
App({
  onLaunch(options) {
    const version = xhs.getSystemInfoSync().SDKVersion;
    const menuButtonObject = xhs.getMenuButtonBoundingClientRect();
    const { statusBarHeight } = xhs.getSystemInfoSync();
    const navTop = menuButtonObject.top;
    const navHeight =
      statusBarHeight +
      menuButtonObject.height +
      (menuButtonObject.top - statusBarHeight) * 2;
    this.globalData.navTop = navTop;
    this.globalData.navHeight = navHeight;
    this.globalData.menuHeight = menuButtonObject.height;
    this.globalData.version = version;
  },
  globalData: {
    info: {
      kf: undefined,
      phone: undefined,
      dyhewm: undefined,
      qwqdm: undefined,
    },
    config: {
      ...require("./config"),
    },
  },
  methods: {
    // 解析后缀
    async getOPtions(options) {
      return new Promise((resolve) => {
        let opObj = {};
        if (options.scene) {
          let opArr = options.scene;
          opArr = opArr.split("-");
          for (let i = 0; i < opArr.length; i++) {
            let zancun = opArr[i].includes(".") ? opArr[i].split(".") : ["", ""];
            opObj[zancun[0]] = zancun[1];
          }
        }
        resolve(opObj);
      });
    },
    // 根据id换正式链接
    async getLink(id) {
      return new Promise((resolve) => {
        hbappRequest({
          url: "/hbqt/web/index.php/Contactus/xcxhdtwo/create_urlinfo?callback=&",
          method: "GET",
          dataType: "jsonp",
          data: {
            ljid: id,
            shijian: Date.parse(new Date()) / 1000,
          },
        })
          .then((res) => {
            let zjz = this.getAPIReturn(res);
            let opArr = [];
            let { str, name } = zjz.data;
            let opObj = {};
            if (str) {
              if (str != null || str != "") {
                if (str.includes("&amp;")) {
                  opArr = str.split("&amp;");
                } else if (str.includes("&")) {
                  opArr = str.split("&");
                } else {
                  opArr[0] = str;
                }
                for (let i = 0; i < opArr.length; i++) {
                  let zancun = opArr[i].includes("=")
                    ? opArr[i].split("=")
                    : ["", ""];
                  opObj[zancun[0]] = zancun[1];
                }
                opObj.name = name;
              }
            }
            resolve(opObj);
          })
          .catch((err) => {
            console.log(err);
            resolve(false);
          });
      });
    },
    // 获取身份信息
    async getIdentity(options) {
      let gonghao = options ? options.gh : "zcj37368";
      getApp().globalData.options = options;
      return new Promise((resolve) => {
        hbappRequest({
          url: "/hbqt/web/index.php/System/department/ajaxcheckuserlists?callback=&",
          method: "GET",
          dataType: "jsonp",
          data: {
            val: gonghao,
          },
        })
          .then((res) => {
            let zjz = this.getAPIReturn(res);
            if (zjz.data.length != 0) {
              let getIdentity = zjz.data[0];
              if (!getIdentity.xulie_name) {
                getIdentity.xulie_name = "";
              }
              let getIdentityObj = {};
              getIdentityObj.getIdentity = getIdentity;
              getIdentityObj.getIdentity = getIdentity;
              resolve(getIdentityObj);
            } else {
              let getIdentityObj = {};
              let getIdentity = {};
              getApp().methods.getIdentity1(
                getIdentityObj,
                getIdentity,
                options
              );
              resolve(getIdentityObj);
            }
          })
          .catch((err) => {
            let getIdentityObj = {};
            let getIdentity = {};
            getApp().methods.getIdentity1(getIdentityObj, getIdentity, options);
            resolve(getIdentityObj);
          });
      });
    },
    // 未检索到个人信息时反馈信息
    getIdentity1: function (getIdentityObj, getIdentity, options) {
      getIdentity.username = options.gh;
      getIdentity.xulie_name = "";
      getIdentity.realname = "";
      getIdentity.wx = "";
      getIdentity.course = "";
      getIdentity.crm = options.gh;
      getIdentityObj.getIdentity = getIdentity;
    },
    // 获取企业微信联系我id
    async getWechat(options) {
      return new Promise((resolve) => {
        let WechatWorkContactMePlugID = {};
        let Wechat = {};
        if (options.wxh) {
          appRequest({
            url: "/apis/suffix/contact-information",
            method: "GET",
            dataType: "jsonp",
            data: {
              "wechat-work-userid": options.wxh,
            },
          })
            .then((res) => {
              let resdata = res.data;
              if (resdata.Userid != "system") {
                Wechat.Wechat = resdata.WechatWorkContactMePlugID;
                Wechat.QrCode = resdata.QrCode;
                WechatWorkContactMePlugID.Wechat = Wechat;
                getApp().globalData.QrCode = resdata.QrCode;
                resolve(WechatWorkContactMePlugID);
              } else {
                Wechat.Wechat = "";
                Wechat.QrCode = "";
                WechatWorkContactMePlugID.Wechat = Wechat;
                resolve(WechatWorkContactMePlugID);
              }
            })
            .catch((err) => {
              Wechat.Wechat = "";
              Wechat.QrCode = "";
              WechatWorkContactMePlugID.Wechat = Wechat;
              resolve(WechatWorkContactMePlugID);
            });
        }
      });
    },
    // 获取分部二维码
    async guishudi(options) {
      let fenxiaoObj = {};
      let fenxiao, fenbu, corde, gzhname, hz19, zzname, zzid, erpdqm;
      if (options.fx == undefined) {
        options.fx = "hb";
      }
      return new Promise((resolve) => {
        zg99Request({
          url: `/index/chaxun/getfzinfo/?callback=&`,
          method: "GET",
          dataType: "jsonp",
          data: {
            actid: 427,
            fenbu: options.fx,
            shijian: Date.parse(new Date()) / 1000
          }
        })
          .then((res) => {
            let zjz = this.getAPIReturn(res);
            fenxiaoObj.fenxiao = zjz.lists[0].houzhui;
            fenxiaoObj.fenbu = zjz.lists[0].fenxiao;
            fenxiaoObj.corde = zjz.lists[0].corde;
            fenxiaoObj.gzhname = zjz.lists[0].gzhname;
            fenxiaoObj.hz19 = zjz.lists[0].hz19;
            fenxiaoObj.zzname = zjz.lists[0].zzname;
            fenxiaoObj.zzid = zjz.lists[0].zzid;
            fenxiaoObj.erpdqm = zjz.lists[0].erpdqm;
            resolve(fenxiaoObj);
          })
          .catch((err) => {
            fenxiaoObj.fenxiao = '河北';
            fenxiaoObj.fenbu = '河北';
            fenxiaoObj.corde = 'https://hb.offcn.com/zg/ycdh/images/hboffcn.jpg';
            fenxiaoObj.gzhname = 'hboffcn';
            fenxiaoObj.hz19 = 'hebei';
            fenxiaoObj.zzname = '河北分校';
            fenxiaoObj.zzid = 4936;
            fenxiaoObj.erpdqm = 3778;
            resolve(fenxiaoObj);
          });
      });
    },
    // 处理接口返回值（zg99和综合系统）
    getAPIReturn(res) {
      let zjz = JSON.parse(res.substring(1, res.length - 1));
      return zjz;
    },
    // 根据后缀获取相关信息
    getCity(infoArr, fenxiao) {
      return new Promise(async (resolve) => {
        let info = {};
        if (fenxiao.indexOf("sjz") == 0) {
          info = infoArr[0];
        } else if (fenxiao.indexOf("bdq") == 0) {
          info = infoArr[12];
        } else if (fenxiao.indexOf("bd") == 0) {
          info = infoArr[1];
        } else if (fenxiao.indexOf("xt") == 0) {
          info = infoArr[2];
        } else if (fenxiao.indexOf("ts") == 0) {
          info = infoArr[3];
        } else if (fenxiao.indexOf("cd") == 0) {
          info = infoArr[4];
        } else if (fenxiao.indexOf("qhd") == 0) {
          info = infoArr[5];
        } else if (fenxiao.indexOf("hdq") == 0) {
          info = infoArr[21];
        } else if (fenxiao.indexOf("hd") == 0) {
          info = infoArr[6];
        } else if (fenxiao.indexOf("cz") == 0) {
          info = infoArr[7];
        } else if (fenxiao.indexOf("zjk") == 0) {
          info = infoArr[8];
        } else if (fenxiao.indexOf("lf") == 0) {
          info = infoArr[9];
        } else if (fenxiao.indexOf("hs") == 0) {
          info = infoArr[10];
        } else if (fenxiao.indexOf("sj") == 0) {
          info = infoArr[11];
        } else if (fenxiao.indexOf("bcq") == 0) {
          info = infoArr[13];
        } else if (fenxiao.indexOf("bhq") == 0) {
          info = infoArr[14];
        } else if (fenxiao.indexOf("jzq") == 0) {
          info = infoArr[15];
        } else if (fenxiao.indexOf("jnq") == 0) {
          info = infoArr[16];
        } else if (fenxiao.indexOf("jhq") == 0) {
          info = infoArr[17];
        } else if (fenxiao.indexOf("wqq") == 0) {
          info = infoArr[18];
        } else if (fenxiao.indexOf("xqq") == 0) {
          info = infoArr[19];
        } else if (fenxiao.indexOf("nhq") == 0) {
          info = infoArr[20];
        } else if (fenxiao.indexOf("zhq") == 0) {
          info = infoArr[22];
        } else {
          info = await this.noFenxiao(infoArr);
        }
        resolve(info);
      });
    },
    // 在无分校后缀时处理
    noFenxiao(infoArr) {
      return new Promise(async (resolve) => {
        let info;
        let isAuthorizer = await this.authorizer();
        if (isAuthorizer == "ok") {
          let locations = await this.getLocation();
          let { city, district } = await this.loadCity(
            locations.longitude,
            locations.latitude
          );
          info = await this.getCityInfo(infoArr, city, district);
        } else {
          info = getApp().methods.randomCity(infoArr);
        }
        resolve(info);
      });
    },
    // 打开咨询界面
    goZixun(kf) {
      xhs.navigateTo({
        url: `/pages/wxArticle/wxArticle?type=zixun&kf=${kf}`,
      });
    },
    // 根据是否授权划定如何获取城市
    authorizer() {
      return new Promise((resolve) => {
        xhs.getSetting({
          success: (res) => {
            if (res.authSetting["scope.userLocation"]) {
              resolve("ok");
            } else {
              xhs.authorize({
                scope: "scope.userLocation",
                success: async (res) => {
                  resolve("ok");
                },
                fail: (err) => {
                  resolve("no");
                },
              });
            }
          },
          fail: (err) => {
            xhs.authorize({
              scope: "scope.userLocation",
              success: async (res) => {
                resolve("ok");
              },
              fail: (err) => {
                resolve("no");
              },
            });
          },
        });
      });
    },
    // 根据当前地市确定对应信息
    getCityInfo: (infoArr, city, district) => {
      return new Promise((resolve) => {
        let info;
        if (city == "石家庄市") {
          info = infoArr[0];
        } else if (city == "保定市") {
          info = infoArr[1];
        } else if (city == "唐山市") {
          info = infoArr[3];
        } else if (city == "承德市") {
          info = infoArr[4];
        } else if (city == "邯郸市") {
          info = infoArr[6];
        } else if (city == "沧州市") {
          info = infoArr[7];
        } else if (city == "秦皇岛市") {
          info = infoArr[5];
        } else if (city == "张家口市") {
          info = infoArr[8];
        } else if (city == "廊坊市") {
          info = infoArr[9];
        } else if (city == "衡水市") {
          info = infoArr[10];
        } else if (city == "邢台市") {
          info = infoArr[2];
        } else if (city == "天津市") {
          if (district == "宝坻区") info = infoArr[12];
          if (district == "北辰区") info = infoArr[13];
          if (district == "滨海区") info = infoArr[14];
          if (district == "蓟州区") info = infoArr[15];
          if (district == "津南区") info = infoArr[16];
          if (district == "静海区") info = infoArr[17];
          if (district == "武清区") info = infoArr[18];
          if (district == "西青区") info = infoArr[19];
          if (district == "宁河区") info = infoArr[20];
          if (district == "河东区") info = infoArr[21];
          if (district == "河西区") info = infoArr[22];
          info = infoArr[11];
        } else {
          info = getApp().methods.randomCity(infoArr);
        }
        resolve(info);
      });
    },
    // 取随机城市（没放天津）
    randomCity(infoArr) {
      return new Promise((resolve) => {
        let num = Math.random() * 10;
        num = Math.floor(num);
        let info = {
          kf: infoArr[num].kf,
          phone: infoArr[num].phone,
          dyhewm: infoArr[num].dyhewm,
          dyh: infoArr[num].dyh,
          qwqdm: infoArr[num].qwqdm,
        };
        resolve(info);
      });
    },
    // 根据经纬度获取当前城市名称
    loadCity(longitude, latitude) {
      return new Promise((resolve, reject) => {
        xhs.request({
          url:
            "https://api.map.baidu.com/geocoder/v2/?ak=5VR2hpxhwV0DmZvGbcUYIS5d&location=" +
            latitude +
            "," +
            longitude +
            "&output=json",
          data: {},
          header: {
            "Content-Type": "application/json",
          },
          success: (res) => {
            // console.log(res.data.result.addressComponent)
            const { city, district } = res.data.result.addressComponent;
            resolve({ city, district });
          },
          fail: (err) => {
            reject();
          },
        });
      });
    },
    // 获取经纬度
    getLocation() {
      return new Promise((resolve) => {
        xhs.getLocation({
          type: "wgs84",
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            console.log(err);
            resolve(false);
          },
        });
      });
    },
    // 获取code并兑换手机号
    getPhoneNumber() {
      return new Promise(async (resolve, reject) => {
        let myPhone = await this.getStorage("myPhone");
        // console.log(myPhone)
        if (!myPhone) {
          let code = await this.getCode();
          let res = await this.getSession_key(code);
          console.log(res)
          if (res.code == 0 && res.message == "Session_key获取成功") {
            getApp().globalData.session_key = res.data.session_key;
            getApp().globalData.openid = res.data.openid;
          } else if (res.code == 0 && res.message == "手机号获取成功") {
            xhs.setStorageSync("myPhone", res.data.phoneNumber);
          }
          resolve(res);
        } else {
          resolve(myPhone);
        }
      });
    },
    // 设置本地存储
    setStorage(key, value) {
      return new Promise((resolve) => {
        xhs.setStorage({
          key,
          data: value,
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            resolve(false);
          },
        });
      });
    },
    // 获取本地存储
    getStorage(key) {
      return new Promise((resolve) => {
        xhs.getStorage({
          key,
          success: (result) => {
            // console.log(result);
            resolve(result);
          },
          fail: (err) => {
            // console.log(err);
            resolve(false);
          },
        });
      });
    },
    // 获取code
    getCode() {
      return new Promise((resolve, reject) => {
        xhs.login({
          success: (res) => {
            resolve(res.code);
          },
          fail: (err) => {
            resolve(false);
          },
        });
      });
    },
    // 获取session_key
    getSession_key(code) {
      return new Promise((resolve, reject) => {
        jiatuiRequest({
          url: "/api/v1/wxxcx/getXhsSession_key",
          method: "GET",
          dataType: "jsonp",
          data: {
            appid: getApp().globalData.config.appid,
            code,
          },
          header: {
            "x-requested-from": "WeChatMiniProgram",
          },
        })
          .then((res) => {
            // console.log(res)
            resolve(res);
          })
          .catch((err) => {
            // console.log(err);
            reject(err);
          });
      });
    },
    // myPhone 获取本地存储手机号
    async myPhone() {
      let obj = {};
      return new Promise(async (resolve) => {
        let res = await this.getStorage("myPhone");
        // console.log(res)
        if (!res.data || res.data == "undefind") {
          xhs.removeStorage({
            key: "myPhone",
          });
          resolve();
        } else {
          obj.myPhone = res.data;
          resolve(obj);
        }
      });
    },
    /**
     * getphonestatusCX 是否注册
     * myPhone：手机号
     * actid：表单号
     * type：表单类别
     */
    async getphonestatusCX(myPhone, actid, type) {
      return new Promise((resolve) => {
        zg99Request({
          url: `/index/${type}/getphonestatus/?actid=${actid}&callback=&`,
          method: "GET",
          dataType: "jsonp",
          data: {
            phone: myPhone,
            shijian: Date.parse(new Date())
          },
        })
          .then((res) => {
            let zjz = this.getAPIReturn(res);
            let user = {};
            if (zjz.status == 1) {
              user.user = zjz;
              resolve(user);
            } else {
              resolve(true);
            }
          })
          .catch((err) => {
            resolve(true);
          });
      });
    },
    /** 查询控制咨询微信号显隐 */
    async getShow(){
      return new Promise((resolve) => {
        zg99Request({
          url: `/index/chaxun/getphonestatus/?actid=57786&callback=&`,
          method: "GET",
          dataType: "jsonp",
          data: {
            phone: '18832121507',
            shijian: Date.parse(new Date())
          },
        })
        .then((res) => {
          let zjz = this.getAPIReturn(res);
          let user = {};
          if (zjz.status == 1) {
            user.user = zjz;
            resolve(user.user.user.isShow);
          } else {
            resolve(true);
          }
        })
        .catch((err) => {
          resolve(true);
        });
      })
    }, 
    /**
     * registerCX 注册
     * myPhone：手机号；actid：表单号；laiyuan：标记来源；isSydw：是否为事业单位活动；getIdentity：推广人信息；bklx：备考类型（可为空）；zkzh：准考证号（可为空）；type：表单类别
     */
    async registerCX(myPhone, actid, laiyuan, isSydw, getIdentity, bklx, zkzh, books, type) {
      var phonegsd = null;
      if (!getIdentity.zzid && getIdentity.fenbu == "河北") {
        phonegsd = await getApp().methods.get_phone_attribution(myPhone);
      }
      return new Promise((resolve) => {
        let orgn = getIdentity.zzid;
        let erpdqm = getIdentity.erpdqm;
        let data = {
          phone: myPhone,
          gonghao: getIdentity.crm != "" ? getIdentity.crm : getIdentity.username,
          fenxiao: getIdentity.fenxiao,
          orgn,
          erpdqm,
          laiyuan: laiyuan + 'xhs',
          books,
          channel: 122,
          c2: '小程序对接',
          remark: `小程序：河北中公，actid：${actid}，推广码：${getIdentity.crm != "" ? getIdentity.crm : getIdentity.username}`,
          xulieName: getIdentity.xulie_name,
          realname: getIdentity.realname,
          isagree: 'true'
        };
        isSydw ? (data.gwlb = bklx) : "";
        isSydw ? (data.project = bklx) : "";
        if (zkzh != "") {
          data.zhunkaozheng = zkzh;
        }
        zg99Request({
          url: `/index/${type}/register/?actid=${actid}&callback=&`,
          method: "GET",
          dataType: "jsonp",
          data: {
            ...data,
            shijian: Date.parse(new Date())
          },
        })
          .then((res) => {
            let zjz = this.getAPIReturn(res);
            resolve(zjz);
          })
          .catch((err) => {
            resolve();
          });
      });
    },
    /**
     * updateuserCX 更新用户表
     * myPhone：手机号；actid：表单号；laiyuan：标记来源；isSydw：是否为事业单位活动；getIdentity：推广人信息；bklx：备考类型（可为空）；zkzh：准考证号（可为空）；type：表单类别；user：已注册所填写信息
     */
    async updateuserCX(
      myPhone,
      actid,
      laiyuan,
      isSydw,
      getIdentity,
      bklx,
      zkzh,
      type,
      book,
      user
    ) {
      return new Promise((resolve) => {
        let thisLy = user.laiyuan;
        let books = user.books;
        if (
          user.gonghao == "无" ||
          user.gonghao == "" ||
          user.gonghao == "" ||
          user.gonghao == null ||
          user.gonghao == "undefined"
        ) {
          user.gonghao =
            getIdentity.crm != "" ? getIdentity.crm : getIdentity.username;
          user.xulieName = getIdentity.xulie_name;
          user.realname = getIdentity.realname;
        }
        if (
          user.fenxiao == "无" ||
          user.fenxiao == "" ||
          user.fenxiao == "null" ||
          user.fenxiao == "null " ||
          user.fenxiao == null
        ) {
          user.fenxiao = getIdentity.fenxiao;
          user.orgn = getIdentity.zzid;
          user.erpdqm = getIdentity.erpdqm;
        }
        if (zkzh != "" && !user.zhunkaozheng) {
          user.zhunkaozheng = zkzh;
        }
        if (!thisLy) {
          user.laiyuan = laiyuan + 'xhs';
        } else if (thisLy.indexOf(laiyuan) < 0) {
          user.laiyuan = thisLy + "," + laiyuan + 'xhs';
        }
        if (!books) {
          user.books = book;
        } else if (books.indexOf(book) < 0) {
          user.books = books + "," + book;
        }
        isSydw
          ? user.gwlb == "" ||
            user.gwlb == "null" ||
            user.gwlb == "null " ||
            !user.gwlb
            ? ((user.gwlb = bklx), (user.project = bklx))
            : user.gwlb
          : true;
        zg99Request({
          url: `/index/${type}/updateuser/?actid=${actid}&callback=&`,
          method: "GET",
          dataType: "jsonp",
          data: {
            phone: user.phone,
            gonghao: user.gonghao,
            fenxiao: user.fenxiao,
            laiyuan: user.laiyuan,
            gwlb: user.gwlb,
            project: user.project,
            books: user.books,
            xulieName: user.xulieName,
            realname: user.realname,
            zhunkaozheng: user.zhunkaozheng,
            orgn: user.zzid,
            erpdqm: user.erpdqm,
            isagree: true,
            shijian: Date.parse(new Date()) / 1000
          },
        })
          .then((res) => {
            let zjz = this.getAPIReturn(res);
            resolve(zjz);
          })
          .catch((err) => {
            resolve();
          });
      });
    },
    /**
     * get_phone_attribution 获取手机归属地
     */
    async get_phone_attribution(phone) {
      return new Promise((resolve, reject) => {
        hbappRequest({
          url: "/hbqt/web/index.php/Contactus/phone_attribution/get_phone_attribution?callback=&",
          method: "GET",
          dataType: "jsonp",
          data: {
            phone,
          },
        })
          .then((res) => {
            let zjz = this.getAPIReturn(res);
            resolve(zjz.data);
          })
          .catch((err) => {
            let zjz = this.getAPIReturn(res);
            resolve(zjz.msg);
          });
      });
    },
    // input输入获取值
    inputInfor(e) {
      let method = e.currentTarget.dataset.method;
      let methodObj = {}
      methodObj[method] = e.detail && e.detail.value
      return methodObj
    },
    // picker输入获取值
    bindPickerChange(e) {
      let method = e.currentTarget.dataset.method;
      let methodObj = {}
      methodObj[method] = e.detail && e.detail.value
      return methodObj
    },
    // 用正则表达式实现html解码（反转义）
    htmlDecodeByRegExp(str) {
      var temp = '';
      // console.log(str)
      if (str) {
        if (str.length == 0) return ''
        temp = str.replace(/&amp;/g, "&");
        temp = temp.replace(/&lt;/g, "<");
        temp = temp.replace(/&gt;/g, ">");
        temp = temp.replace(/&nbsp;/g, " ");
        temp = temp.replace(/&#39;/g, "\'");
        temp = temp.replace(/&quot;/g, "\"");
        return temp;
      } else {
        return ''
      }
    },
    /**
     * 获取是否开课
     */
    sfkkMethod: function (spu_id, user_phone) {
      return new Promise((resolve, reject) => {
        eoffcnRequest({
          url: `/erp/api/user/order_list/by_spu_ids`,
          method: 'POST',
          header: {
            Authorization: `Basic OTU5YjcxYmYyZGNlYTI1NjExZjg1MmQ0Yzk0ZTE2MDA6ZTM0ZDcyZDE4YTQ2ZDRjZjAxZjY2NjRiODZlZTRiODk=`
          },
          data: {
            user_phone,
            spu_id,
            platform_id: ''
          },
        }).then(res => {
          console.log(res);
          resolve(res.data)
        }).catch(err => {
          console.log(err);
          resolve()
        })
      })
    },
    // 开课
    zidongkaike: function (spu_id, user_phone, source_name, remark, user_name) {
      return new Promise((resolve, reject) => {
        eoffcnRequest({
          url: '/erp/api/order/create_and_complete',
          method: 'POST',
          header: {
            Authorization: `Basic OTU5YjcxYmYyZGNlYTI1NjExZjg1MmQ0Yzk0ZTE2MDA6ZTM0ZDcyZDE4YTQ2ZDRjZjAxZjY2NjRiODZlZTRiODk=`
          },
          data: {
            user_name,
            user_phone,
            goods: [{
              spu_id,
              pay_money: 0,
            }],
            source_name,
            source: 2,
            remark
          },
        }).then(res => {
          console.log(res)
          resolve(res.data)
        }).catch(err => {
          console.log(err)
          reject()
        })
      })
    },
    /**
     * compareVersion 兼容性版本计算
     */
    compareVersion: function (v1, v2) {
      v1 = v1.split('.')
      v2 = v2.split('.')
      const len = Math.max(v1.length, v2.length)
      while (v1.length < len) {
        v1.push('0')
      }
      while (v2.length < len) {
        v2.push('0')
      }
      for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i])
        const num2 = parseInt(v2[i])
        if (num1 > num2) {
          return 1
        } else if (num1 < num2) {
          return -1
        }
      }
      return 0
    },

    // 获取授权信息
    authorizeInfo(setting) {
      return new Promise((resolve) => {
        xhs.getSetting({
          success: (res) => {
            console.log(res)
            if (res.authSetting[setting]) {
              resolve(true);
            } else {
              resolve(false)
            }
          },
          fail: (err) => {
            console.log(err);
            resolve(err)
          },
        });
      });
    },
    // 获取用户信息
    getUserProfile() {
      return new Promise((resolve) => {
        xhs.getUserProfile({
          desc: "获取用户信息",
          success: (res) => {
            console.log(res);
            resolve(res);
          },
          fail: (err) => {
            console.log(err);
            resolve(err);
          },
        });
      });
    },
    // 授权
    getAuth(scope) {
      return new Promise((resolve) => {
        xhs.authorize({
          scope,
          success: (res) => {
            console.log("授权成功", res);
            resolve(res);
          },
          fail: (err) => {
            console.log("授权失败", err);
            resolve(err);
          },
        });
      });
    },
    // 上传图片
    updateAvatar(tempFilePath) {
      return new Promise((resolve, reject) => {
        uploadFileRequest({
          url: `/api/v1/pk/uploadImg`,
          method: 'post',
          filePath: tempFilePath,
          header: {
            'X-Requested-From': 'WeChatMiniProgram',
          },
          name: 'file',
        }).then(res => {
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      })
    },
  },
});
